package org.bees.cms.web.action.io;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.bees.cms.common.Order;
import org.bees.cms.common.Page;
import org.bees.cms.core.io.Directory;
import org.bees.cms.core.io.Document;
import org.bees.cms.core.io.IO;
import org.bees.cms.service.Service;
import org.bees.cms.web.action.LocalizableAction;
import org.bees.cms.web.action.PagingActionSupport;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Scope("prototype")
@Controller
public class FilePagingAction extends PagingActionSupport<IO> implements LocalizableAction<Directory> {
	private String path = "";
	private Scope scope = Scope.ALL;
	private Directory node;

	@Override
	public Service<IO> service() {
		return null;
	}

	@Override
	protected Page<IO> query(long current, long capacity, String condition, Order order, String by) throws Exception {
		File root = new File(context.getRealPath(path));

		List<IO> domains = new ArrayList<IO>();
		if (root.isDirectory()) {
			Directory parent = new Directory();
			parent.from(root);

			File[] files = root.listFiles();
			List<Directory> directories = new ArrayList<Directory>();
			List<Document> documents = new ArrayList<Document>();
			for (File file : files) {
				if ((scope == Scope.ALL || scope == Scope.DIRECTORY) && file.isDirectory() && !file.isHidden()) {
					Directory directory = new Directory();
					directory.from(file);
					directory.setParent(parent);
					directories.add(directory);
				}
				if ((scope == Scope.ALL || scope == Scope.DOCUMENT) && file.isFile() && !file.isHidden()) {
					Document document = new Document();
					document.from(file);
					document.setDirectory(parent);
					documents.add(document);
				}
			}

			domains.addAll(directories);
			domains.addAll(documents);

			node = parent;
		} else if (root.isFile()) {
			Document document = new Document();
			document.from(root);
			domains.add(document);

			node = document.getDirectory();
		}

		Page<IO> page = new Page<IO>();
		page.setCurrent(current);
		page.setCapacity(capacity);
		page.setCondition(condition);
		page.setOrder(order);
		page.setBy(by);
		page.setDomains(domains);
		page.setTotal(domains.size());

		return page;
	}

	public enum Scope {
		ALL, DOCUMENT, DIRECTORY;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public Scope getScope() {
		return scope;
	}

	public void setScope(Scope scope) {
		this.scope = scope;
	}

	@Override
	public Directory getNode() {
		return node;
	}

	@Override
	public void setNode(Directory node) {
		this.node = node;
	}

}
